const router = require("express")();
const dm = require("../core/DataManager");
const um = require("../core/UserManager");
const mm = require("../core/MailManager");
const fm = require("../core/FileManager");
const ltt = NCUTCAT.localProperty.login_token_time * 60 * 1000;
// auth
router.post('/auth', function(req, res, next) {
    let param = req.body;
    let n = param.username || "";
    let p = param.password || "";
    let t = param.time || "";
    if (n && p && t)
        um.getToken(n, p, t, (err, token) => {
            if (!err) res.cookie('login-token', token, { expires: new Date(Date.now() + ltt) })
            res.json({
                success: !err,
                message: err || token
            });
        });
    else
        res.json(RES_CHECKER({ success: false, message: "bad data" }));
});

router.all('/logout', (req, res) => res.cookie('login-token', "").status(200).end());

router.all('/check-login', um.middle_finder, um.middle_loadUser, (req, res) => {
    if (!req.user) return res.json(RES_CHECKER({ success: false }));
    res.json({
        success: true,
        info: { uid: req.user.uid, nick: req.user.nick, name: req.user.name },
        permission: um.getPermissions(req.user),
    });
});

router.all('/fans-count', um.middle_checker, um.middle_loadUser, (req, res) => dm.getUserFansCount(req.user.uid, DM_RES(res, 'count')));
router.all('/fans', um.middle_checker, um.middle_loadUser, (req, res) => dm.getUserFans(req.user.uid, req.query.page || 0, DM_RES(res)));
router.all('/follows-count', um.middle_checker, um.middle_loadUser, (req, res) => dm.getUserFollowsCount(req.user.uid, DM_RES(res, 'count')));
router.all('/follows', um.middle_checker, um.middle_loadUser, (req, res) => dm.getUserFollows(req.user.uid, req.query.page || 0, DM_RES(res)));

router.all('/follow', um.middle_checker, um.middle_loadUser, (req, res) => {
    let fid = (req.query || {}).fid || (req.body || {}).fid;
    let isPrivate = (req.query || {}).isPrivate || (req.body || {}).isPrivate;
    let isSpecial = (req.query || {}).isSpecial || (req.body || {}).isSpecial;
    let group = (req.query || {}).group || (req.body || {}).group;
    dm.setUserFollow(req.user.uid, fid, isPrivate == 'true', isSpecial == 'true', group, DM_RES(res));
});

router.get('/set-sketchIcon', um.middle_checker, um.middle_loadUser, (req, res) => {
    let uid = req.user.uid;
    let icon = req.query.icon || null;
    if (icon && !fm.iconsMap[icon]) return res.json(RES_CHECKER({ success: false, err: 'Not Found' }));

    dm.setUserSketchIcon(uid, icon, DM_RES(res, 'uid'));
});

router.all('/getUserInfo/:k', um.middle_finder, um.middle_loadUser, (req, res) => {
    let uid = req.params.k;
    if (!uid) return res.json(RES_CHECKER({ success: false, err: "NaN" }));

    dm.getUserByID(uid, async (err, result) => {
        if (err) return res.json(RES_CHECKER({ success: false, err: err }));
        if (!result) return res.json(RES_CHECKER({ success: true, result: null }));
        let r = {
            uid: uid,
            name: result.name,
            nick: result.nick,
            p_a: result.p_a
        };
        if (req.user) r.follow = await dm.hasUserFollow(req.user.uid, uid);
        return res.json(RES_CHECKER({ success: true, result: r }));
    });
});

router.all('/getUser/all/:k/:p', um.middle_checker, um.middle_loadUser, (req, res) => {
    let user = req.user;
    if (!um.permissionCheck(true, user, "check_user")) return res.json(RES_CHECKER({ success: false, err: "权限不足" }));

    let params = req.params;
    let key = params.k || "";
    let page = params.p || 0;

    key = decodeURI(key);
    page = decodeURI(page);

    dm.getAllUser(key, page, 127, (err, result) => {
        if (err) {
            NCUTCAT.error('查询通知时出错');
            return res.json(RES_CHECKER({ success: false, err: "查询通知时出错" }));
        }
        res.json(RES_CHECKER({ success: true, result: result }));
    })
});


const inviteCode = new Set();
/**
 * 创建邀请码
 * */
router.all('/invite/create', um.middle_checker, um.middle_loadUser, (req, res) => {
    if (!um.permissionCheck(true, req.user, "create_invite_code")) return res.json(RES_CHECKER({ success: false, err: "权限不足" }));
    let query = req.query;
    let amount = parseInt(query.amount);
    if (isNaN(amount)) return res.json(RES_CHECKER({ success: false, err: "NaN" }));
    amount += inviteCode.size;
    if (amount > 500) return res.json(RES_CHECKER({ success: false, err: "Too many" }));
    while (inviteCode.size < amount) {
        let code = NCUTCAT.tools.randomString(32);
        inviteCode.add(`I_${code}`);
    }
    return res.json(RES_CHECKER({ success: true, amount: inviteCode.size }));
});
router.all('/invite/get', um.middle_checker, um.middle_loadUser, (req, res) => {
    if (!um.permissionCheck(true, req.user, "see_invite_code")) return res.json(RES_CHECKER({ success: false, err: "权限不足" }));
    res.json(RES_CHECKER({ success: true, result: [...inviteCode] }));
});


const emailCoolDown = {};
const verifyCode = {};
const emailReg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
const evt = NCUTCAT.localProperty.emailVerify_timeout;
const evr = NCUTCAT.localProperty.emailVerify_resend;
router.get('/register/verify-email', async (req, res) => {
    let param = req.query;
    let mail = param.email;
    let code = param.code;
    let invite = param.invite;
    if (code) {
        return res.json(RES_CHECKER(verifyCode[mail] === code)); //验证
    }
    code = NCUTCAT.tools.randomString(6);

    if (!inviteCode.has(invite)) return res.json(RES_CHECKER({ success: false, err: '无效邀请码' }));
    if (!emailReg.test(mail)) return res.json(RES_CHECKER({ success: false, err: '无效邮箱' }));
    if (emailCoolDown[invite]) return res.json(RES_CHECKER({ success: false, err: '冷却中' }));

    verifyCode[mail] = code;
    emailCoolDown[invite] = code;

    setTimeout(() => { if (verifyCode[mail] === code) delete verifyCode[mail]; }, evt);
    setTimeout(() => { if (emailCoolDown[invite] === code) delete emailCoolDown[invite]; }, evr);

    let err = await mm.sendVerifyEmail(mail, code);
    if (err) return res.json(RES_CHECKER({ success: false, err: err }));
    res.json(RES_CHECKER({ success: true, evt: evt, evr: evr }));
});

router.post('/register/auth', (req, res) => {
    let param = req.body || {};
    let username = param.username;
    let password = param.password;
    let email = param.email;
    let idCode = param.idCode;
    let invite = param.invite;

    if (verifyCode[email] !== idCode) return res.json(RES_CHECKER({ success: false, err: '无效验证码' }));
    if (!inviteCode.delete(invite)) return res.json(RES_CHECKER({ success: false, err: '无效邀请码' }));


    dm.createUser(username, password, email, invite, (err, result) => {
        if (err) return res.json(RES_CHECKER({ success: false, err: err }));
        res.json(RES_CHECKER({ success: true, result: username }));
        NCUTCAT.infoLog('register', `${username} - ${result}`);
    });
});


//模块导出
module.exports = router;